import React, { useRef, FC, ReactElement } from 'react';
import { ITodo } from '../typings';

// 函数组件基本写法 都是FC 类型，接收外界参数的集合，都有返回值ReactElement(JSX)
interface IProps {
  addTodo: (todo: ITodo) => void;
  todoList: ITodo[];
}

// eslint-disable-next-line no-empty-pattern
const TdInput: FC<IProps> = ({
  addTodo,
  todoList
}): ReactElement => {

  const inputRef = useRef<HTMLInputElement>(null);

  const addItem = (): void => {
    const val: string = inputRef.current!.value.trim()
    if (val.length) {
      const isExist = todoList.find((item: ITodo) => item.content === val);
      if (isExist) {
        alert('输入项已存在！');
        return
      }
      addTodo({
        id: new Date().getTime(),
        content: val,
        completed: false
      })
      inputRef.current!.value = '';
    }
  }

  return (
    <div className="todo-input">
      <input type="text" placeholder="请输入代办事项" ref={ inputRef } />
      <button onClick={ addItem }>增加</button>
    </div>
  );
}

export default TdInput;